package com.example.exam.shiro;

import com.example.exam.user.model.UserBean;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

/**
 * shiro工具类
 */
public class ShiroUtils {

	/**
	 * 返回当前登录的认证实体ID
	 */
	public static String getToken() {
		ShiroPrincipal principal = getPrincipal();
		if (principal != null)
			return principal.getToken();
		return null;
	}

	/**
	 * 返回当前登录的认证实体ID
	 */
	public static Integer getUserId() {
		ShiroPrincipal principal = getPrincipal();
		if (principal != null)
			return principal.getUserId();
		return null;
	}

	/**
	 * 返回当前登录的认证实体区域ID
	 * @return
	 */
	public static String getAreaId() {
		ShiroPrincipal principal = getPrincipal();
		if (principal != null)
			return principal.getAreaId();
		return null;
	}

	/**
	 * 获取当前登录的认证实体
	 * @return
	 */
	public static ShiroPrincipal getPrincipal() {
		Subject subject = SecurityUtils.getSubject();
		return (ShiroPrincipal) subject.getPrincipal();
	}

	/**
	 *******************************************
	 * @title:获取当前登陆用户信息 
	 * @date:Apr 3, 2019
	 * @param: @return  参数说明 
	 * @return:SysUserBean
	 *******************************************
	 */
	public static UserBean getLoginUser() {
		ShiroPrincipal principal = getPrincipal();
		if (principal != null)
			return principal.getUser();
		return null;
	}

	/**
	 * 获取当前认证实体的用户名称
	 */
	public static String getUserName() {
		ShiroPrincipal principal = getPrincipal();
		if (principal != null)
			return principal.getUserName();
		throw new RuntimeException("user's name is null.");
	}

	/**
	 * 获取当前认证实体的登录名称
	 */
	public static String getLoginName() {
		ShiroPrincipal principal = getPrincipal();
		if (principal != null)
			return principal.getLoginName();
		throw new RuntimeException("user's login name is null.");
	}

	/**
	 * 获取是否有操作权限
	 */
	public static boolean hasPermission(String name) {
		Subject currentUser = SecurityUtils.getSubject();
		return currentUser.isPermitted(name);
	}

	/**
	 * 获取是否有角色身份
	 */
	public static boolean hasRole(String name) {
		Subject currentUser = SecurityUtils.getSubject();
		return currentUser.hasRole(name);
	}

	/**
	 * 通过输入账号密码正常登陆的，即使用subject.login(token);登陆。
	 * 用于做一些重要的操作检查
	 */
	public static Boolean isAuthenticated() {
		Subject subject = SecurityUtils.getSubject();
		if (subject.isRemembered() || subject.isAuthenticated()) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 通过记住我登陆的，并没有出现输入账号密码页面
	 * 做一些不太重要的操作
	 */
	public static Boolean isRemembered() {
		Subject subject = SecurityUtils.getSubject();
		if (subject.isRemembered() || subject.isAuthenticated()) {
			return true;
		} else {
			return false;
		}
	}

}
